package Service;

import DAO.UserDAO;
import DATA.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "register",value = "/register")
public class Register extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("firstPassword");
        String email=req.getParameter("email");
        //找名字
        User ans= null;
        try {
            ans = UserDAO.FindbyName(username);
        } catch (SQLException e) {
            throw new RuntimeException("数据查询错误");
        }
        if(ans!=null){
            //存在则不能注册
            resp.getWriter().write("账号已存在");
            req.setAttribute("cannot","账号已存在");
            req.getRequestDispatcher("Register.jsp").forward(req,resp);
        }
        else{
            //注册账号并返回登陆界面
            if(email==null){
                ans=new User(username,password,"");
            }
            else{
                ans=new User(username,password,email);
            }
            try {
                if(UserDAO.insertUser(ans)){
                    req.setAttribute("ifRegister",true);
                }
            } catch (SQLException e) {
                throw new RuntimeException("插入失败");
            }
            req.getRequestDispatcher("Login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
